package com.example.fw;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactData;

public class ContactHelper extends HelperBase {
	
	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
	public void goToCreateContactPage() {
		click(By.linkText("add new"));
	}
	public void fillContactCreationForms(ContactData contact, boolean hasGroupSelector) { 
		type(By.name("firstname"), contact.firstname);
		type(By.name("lastname"), contact.lastname);
		type(By.name("address"), contact.address);
		type(By.name("home"), contact.homephone);
		type(By.name("mobile"), contact.mobilephone);
		type(By.name("work"), contact.workphone);
		type(By.name("email"), contact.email1);
		type(By.name("email2"), contact.email2);
		selectByText(By.name("bday"), contact.birthday);
		selectByText(By.name("bmonth"), contact.birthmonth);
		type(By.name("byear"), contact.birthyear);
		//if (hasGroupSelector) {
		//	selectByText(By.name("new_group"), contact.groupselect);		
		//} else {
		//	if (driver.findElements(By.name("new_group")).size() != 0);{
		//		throw new Error("Group Selector exists in contact modification form");
		//	}
		//}
		type(By.name("address2"), contact.address2);
		type(By.name("phone2"), contact.home); 
	}

	public void submitContact() {
		driver.findElement(By.name("submit")).click();
	}
	public void goToMainPage() {
		driver.get(manager.baseUrl + "/addressbookv4.1.4/");
	}
	public void goBackToMainPage() {
		driver.findElement(By.linkText("home page")).click();
	}
	public void goToContactEditPage(int index) {
		driver.findElement(By.xpath("(//img[@alt='Edit'])[" + index + "]")).click();
		}
	public void deleteContact() {
		driver.findElement(By.xpath("/html/body/div/div[4]/form[2]/input[2]")).click();		
		//delete button has a very strange name parameter - "update"
	}
	public void submitContactModification() {
		driver.findElement(By.xpath("/html/body/div/div[4]/form/input[11]")).click();		
	}
	public List<ContactData> getContacts() {
		List<ContactData> contacts = new ArrayList<ContactData>();
		List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			ContactData contact = new ContactData();
			String title = checkbox.getAttribute("title");
			contact.firstname = title.substring("Select (".length(), title.length() - ")".length());
			contacts.add(contact);
		}
		return contacts;

	}



}
